<?php
declare (strict_types=1);

namespace app\common\model;

use ffhome\frame\model\BaseModel;
use think\facade\Db;

class TallyProgressMonth extends BaseModel
{
    const MODEL_NAME = 'tally_progress_month';
    /**
     * 工作考评：未安排
     */
    const APPRAISE_NONE = 1;

    public static function generate(string $month)
    {
        $customList = TallyCustom::getList();
        foreach ($customList as $custom) {
            if (!self::findByCustomIdAndMonth($custom['id'], $month)) {
                self::generateProcessMonth($custom, $month);
            }
        }
    }

    private static function findByCustomIdAndMonth($customId, $month)
    {
        return Db::name(self::MODEL_NAME)
                ->where(['custom_id' => $customId, 'progress_month' => $month])
                ->limit(1)->count() != 0;
    }

    private static function generateProcessMonth($custom, string $month)
    {
        $userId = currentUserId();
        $now = date('Y-m-d H:i:s');
        Db::name(self::MODEL_NAME)->insert([
            'custom_id' => $custom['id'],
            'accounting_id' => $custom['accounting_id'],
            'progress_month' => $month,
            'estimate_time' => $custom['estimate_time'],
            'create_by' => $userId,
            'create_time' => $now,
            'update_by' => $userId,
            'update_time' => $now,
        ]);
    }

    public static function findByCustomId($id)
    {
        return Db::name(self::MODEL_NAME)->whereIn('custom_id', $id)
                ->limit(1)->count() != 0;
    }

    public static function getMonthListByDayId($dayId)
    {
        $day = TallyProgressDay::get($dayId);
        if (empty($day)) return [];
        return self::getMonthListByDate($day['progress_date']);
    }

    private static function getMonthListByDate($date)
    {
        $month = date('Y-m-01', strtotime($date));
        return Db::name(self::MODEL_NAME)->alias('m')
            ->leftJoin(TallyCustom::MODEL_NAME . ' c', "c.id=m.custom_id")
            ->field('m.id,concat(c.number,c.name) custom_name')
            ->where(['m.progress_month' => $month])
            ->order('c.number', 'asc')->select()->toArray();
    }

    public static function updateAccountingId($customId, $accountingId)
    {
        Db::name(self::MODEL_NAME)
            ->where([['custom_id', '=', $customId], ['progress_month', '>=', date('Y-m') . '-01']])
            ->update(['accounting_id' => $accountingId]);
    }
}